from django import forms
from django.core.exceptions import ValidationError
from web.forms.Bootstrap import BootstrapForm
from web.forms.widgets import ColorRadioSelect
from web import models
class ProjectModelForm(BootstrapForm,forms.ModelForm):
    bootstrap_class_exclude = ['color']

    # desc = forms.CharField(widget.Textarea())
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea,
            'color': ColorRadioSelect(attrs={'class':'color-radio'})
        }

    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request

    def clean_name(self):
        '''项目校验'''
        # 1. 当前用户是否已经创建过同名项目
        name = self.cleaned_data['name']
        exists = models.Project.objects.filter(name=name,creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('项目名已存在')
        # 2. 当前用户是否还有项目额度创建
        # 当前用户的可建项目数self.request.tracer.price_policy.project_num
        # 当前用户已创建的项目数
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('可创建项目为0，如有需要请购买套餐')
        return name